// 专门测试提醒API的问题
const BASE_URL = 'http://localhost:5000/api';

async function testReminderAPI() {
  console.log('🔍 测试提醒API...\n');
  
  try {
    // 1. 登录
    const loginResponse = await fetch(`${BASE_URL}/auth/login/email`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: 'admin@aide.com',
        password: 'admin123456'
      })
    });
    
    const loginData = await loginResponse.json();
    if (!loginResponse.ok) {
      console.log('❌ 登录失败:', loginData);
      return;
    }
    
    const token = loginData.token;
    console.log('✅ 登录成功');
    
    // 2. 创建一个即将到期的任务
    const now = new Date();
    const futureDate = new Date(now.getTime() + 30 * 60 * 1000); // 30分钟后
    
    console.log(`\n📅 创建任务，截止时间: ${futureDate.toISOString()}`);
    
    const taskResponse = await fetch(`${BASE_URL}/tasks`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        title: '测试提醒任务',
        description: '用于测试提醒功能',
        dueDate: futureDate.toISOString(),
        reminderMinutes: 60, // 60分钟前提醒（已经过了提醒时间）
        priority: 'P1',
        category: 'work'
      })
    });
    
    const taskData = await taskResponse.json();
    if (!taskResponse.ok) {
      console.log('❌ 任务创建失败:', taskData);
      return;
    }
    
    console.log('✅ 任务创建成功，ID:', taskData.id);
    
    // 3. 验证任务数据
    const getResponse = await fetch(`${BASE_URL}/tasks/${taskData.id}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    
    const savedTask = await getResponse.json();
    if (getResponse.ok) {
      console.log('📋 任务详情:');
      console.log(`   标题: ${savedTask.title}`);
      console.log(`   截止时间: ${savedTask.dueDate}`);
      console.log(`   提醒间隔: ${savedTask.reminder_minutes} 分钟`);
      
      // 计算提醒时间
      const dueDate = new Date(savedTask.dueDate);
      const reminderTime = new Date(dueDate.getTime() - (savedTask.reminder_minutes * 60 * 1000));
      console.log(`   提醒时间: ${reminderTime.toISOString()}`);
      console.log(`   当前时间: ${now.toISOString()}`);
      console.log(`   应该提醒: ${reminderTime <= now && dueDate > now ? '是' : '否'}`);
    }
    
    // 4. 直接测试提醒检查API
    console.log('\n🔔 测试提醒检查API...');
    
    const reminderResponse = await fetch(`${BASE_URL}/notifications/check-reminders`, {
      method: 'POST',
      headers: { 
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    console.log(`状态码: ${reminderResponse.status}`);
    console.log(`状态文本: ${reminderResponse.statusText}`);
    
    if (reminderResponse.ok) {
      const reminders = await reminderResponse.json();
      console.log('✅ 提醒检查成功');
      console.log(`找到 ${reminders.length} 个提醒任务`);
      
      if (reminders.length > 0) {
        console.log('提醒详情:');
        reminders.forEach((reminder, index) => {
          console.log(`  ${index + 1}. ${reminder.title} (${reminder.reminderMinutes}分钟前)`);
        });
      }
    } else {
      const errorText = await reminderResponse.text();
      console.log('❌ 提醒检查失败');
      console.log('错误响应:', errorText);
      
      try {
        const errorData = JSON.parse(errorText);
        console.log('错误详情:', errorData);
      } catch (e) {
        console.log('无法解析错误响应为JSON');
      }
    }
    
    // 5. 测试通知设置
    console.log('\n⚙️ 检查通知设置...');
    const settingsResponse = await fetch(`${BASE_URL}/notifications/settings`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    
    if (settingsResponse.ok) {
      const settings = await settingsResponse.json();
      console.log('✅ 通知设置获取成功');
      console.log('设置详情:', settings);
    } else {
      console.log('❌ 无法获取通知设置');
    }
    
    // 6. 清理
    await fetch(`${BASE_URL}/tasks/${taskData.id}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${token}` }
    });
    console.log('\n✅ 测试数据已清理');
    
  } catch (error) {
    console.log('❌ 测试过程中发生错误:', error.message);
    console.log('错误堆栈:', error.stack);
  }
}

testReminderAPI();
